//
//  UILabelExample.swift
//  SwiftCode
//
//  Created by yuhus on 2023/12/20.
//

import Foundation
import SnapKit

class UILabelExample: ListViewController {
  override func getItemCount() -> Int {
    data.count
  }
  
  override func getItem(_ indexPath: IndexPath) -> Item {
    data[indexPath.row]
  }
  
  private lazy var data: [Item] = [
    .init(title: "图文混排", description: "图片显示异常", action: { [weak self] in self?.setAttributedText() }),
  ]
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    view.addSubview(label)
    label.snp.makeConstraints { make in
      make.center.equalToSuperview()
    }
  }
  
  private var label = UILabel()
  
  private func setAttributedText() {
    label.text = "显示一个名称"
    label.setUserTag(official: true, offsetY: -1.5)
  }
}

public extension UILabel {
  func setUserTag(official: Bool = true, offsetY: CGFloat = 0) {
    guard official, let text, let image = UIImage(named: "account_verified") else { return }
    var attributes: [NSAttributedString.Key: Any] = [:]
    attributes[.font] = font
    attributes[.foregroundColor] = textColor
    
    let mutableAttributedString = NSMutableAttributedString(string: text, attributes: attributes)
    
//    let attachment = NSTextAttachment(image: image) 图片显示轮廓+字体颜色渲染
    let attachment = NSTextAttachment()
    attachment.image = image
    attachment.bounds = CGRect(x: 0, y: offsetY, width: image.size.width, height: image.size.height)
    let imageAttributedString = NSAttributedString(attachment: attachment)
    
    mutableAttributedString.append(NSAttributedString(string: " "))
    mutableAttributedString.append(imageAttributedString)
    
    attributedText = mutableAttributedString
  }
}

